package com.example.demo.service;

import com.example.demo.domain.FileUploadResponse;
import com.example.demo.domain.WorkflowRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
public class DifyService {

    private static final Logger logger = LoggerFactory.getLogger(DifyService.class);

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 这里请替换成你的实际配置
    private final String difyApiKey = "YOUR_DIFY_API_KEY";
    private final String difyApiUrl = "https://api.dify.ai";

    private final String userId = "abc-123"; // 可动态修改

    /**
     * 上传 MultipartFile 到 Dify，返回文件ID。
     */
    public String uploadFile(MultipartFile file) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String uploadUrl = difyApiUrl + "/v1/files/upload";

            HttpPost httpPost = new HttpPost(uploadUrl);
            httpPost.setHeader("Authorization", "Bearer " + difyApiKey);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(),
                    ContentType.create(file.getContentType()),
                    file.getOriginalFilename());
            builder.addTextBody("user", userId);

            httpPost.setEntity(builder.build());

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                logger.info("上传文件响应状态：{}, 内容：{}", statusCode, responseBody);

                if (statusCode == 200) {
                    FileUploadResponse uploadResponse = objectMapper.readValue(responseBody, FileUploadResponse.class);
                    return uploadResponse.getId();
                } else {
                    throw new IOException("上传文件失败，状态码：" + statusCode);
                }
            }
        }
    }

    /**
     * 使用本地 File 上传到 Dify（配合COS临时文件）。
     */
    public FileUploadResponse uploadFile(File file, String user) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String uploadUrl = difyApiUrl + "/v1/files/upload";

            HttpPost httpPost = new HttpPost(uploadUrl);
            httpPost.setHeader("Authorization", "Bearer " + difyApiKey);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
            if (user != null) {
                builder.addTextBody("user", user);
            }

            httpPost.setEntity(builder.build());

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                logger.info("上传文件响应状态：{}, 内容：{}", statusCode, responseBody);

                if (statusCode == 200) {
                    return objectMapper.readValue(responseBody, FileUploadResponse.class);
                } else {
                    throw new IOException("上传文件失败，状态码：" + statusCode);
                }
            }
        }
    }

    /**
     * 调用Dify工作流接口，传入工作流请求体，返回响应字符串。
     */
    public String runWorkflow(WorkflowRequest workflowRequest) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String workflowUrl = difyApiUrl + "/v1/workflows/run";

            HttpPost httpPost = new HttpPost(workflowUrl);
            httpPost.setHeader("Authorization", "Bearer " + difyApiKey);
            httpPost.setHeader("Content-Type", "application/json");

            String jsonBody = objectMapper.writeValueAsString(workflowRequest);
            httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                logger.info("运行工作流响应状态：{}, 内容：{}", statusCode, responseBody);

                if (statusCode == 200) {
                    return responseBody;
                } else {
                    throw new IOException("运行工作流失败，状态码：" + statusCode);
                }
            }
        }
    }

    /**
     * 从 COS 下载文件到临时文件。
     */
    public File downloadFromCos(String cosUrl) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(cosUrl);

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();

                File tempFile = File.createTempFile("cos-download-", ".tmp");
                try (FileOutputStream out = new FileOutputStream(tempFile)) {
                    entity.writeTo(out);
                }
                return tempFile;
            }
        }
    }
}
